# coding:utf-8
import queue
import threading
import time
import random
import requests
import redis

from selenium import webdriver


class Main(threading.Thread):
    def __init__(self, que, debug=False):
        threading.Thread.__init__(self)
        self._queue = que
        self.debug = debug
        self.UAS = open('UA', 'r', encoding='utf-8')
        self.get_ip = requests.get(
            'http://http.tiqu.qingjuhe.cn/getip?num=1&type=2&pro=0&city=0&yys=0&port=1&pack=31395&ts=1&ys=0&cs=0&'
            'lb=1&sb=0&pb=45&mr=0&regions=110000,130000,140000,150000,210000,310000,320000,330000,340000,350000,3'
            '60000,370000,410000,420000,430000,440000,500000,510000,530000,610000,620000,640000')
        self.chromeOptions = webdriver.ChromeOptions()
        self.ip = self.get_ip.json()['data'][0]['ip']
        self.port = self.get_ip.json()['data'][0]['port']
        print('{}:{}'.format(self.ip, self.port))
        self.chromeOptions.add_argument("--proxy-server=http://{0}:{1}".format(self.ip, self.port))
        self.ua = random.sample(self.UAS.readlines(), 1)[0]
        self.UAX = 'user-agent="{0}"'.format(self.ua.replace('\n', ''))
        print(self.UAX)
        self.chromeOptions.add_argument(self.UAX)
        self.rest_ip = requests.get('http://ty-http-d.upupfile.com/index/index/get_my_pack_info?neek=525244&'
                                   'appkey=c7d2367a80ba604f04c704172df92815')
        print('剩余可用IP个数:{0}'.format(self.rest_ip.json()['data'][1]['balance']))
        self.driver = webdriver.Chrome(chrome_options=self.chromeOptions)

    def main(self, keyword):
        self.keyword = eval(keyword)[0]
        self.url = eval(keyword)[1]
        self.driver.get("http://www.baidu.com")
        self.driver.find_element_by_xpath('//*[@id="kw"]').send_keys(self.keyword)
        # 点击百度一下
        self.driver.find_element_by_xpath('//input[@id="su"]').click()
        self.flag = False
        self.page = 0
        while True:
            time.sleep(3)
            self.a_link_list = self.driver.find_elements_by_xpath('//h3[starts-with(@class,"t")]')
            for i in range(len(self.a_link_list)):
                try:
                    self.tmp = self.driver.find_elements_by_xpath(
                        '//h3[starts-with(@class,"t")]/../div[@class="f13"]/a[1]')[i].text.replace('/', '')
                    # print(self.tmp)
                    if self.url in self.tmp:
                        print("OK")
                        self.flag = True
                        self.driver.find_elements_by_xpath('//h3[starts-with(@class,"t")]/../div[@class="f13"]/a[1]')[i].click()
                        time.sleep(5)
                        self.driver.close()
                        r.incr(self.keyword)
                        return
                except IndexError:
                    pass
            self.page += 1
            print(self.page)
            if not self.flag:
                try:
                    if self.page == 1:
                        self.driver.find_element_by_xpath('//a[@class="n"]').click()
                    else:
                        self.driver.find_element_by_xpath('//a[@class="n"][2]').click()
                except:
                    print("关键词'{}'无搜索结果".format(self.keyword))
                    break

    def run(self):
        while not self._queue.empty():
            keyword = self._queue.get_nowait()
            self.main(keyword)


if __name__ == '__main__':
    global q
    pool = redis.ConnectionPool(host='129.28.67.244')
    r = redis.Redis(connection_pool=pool)
    keywords = open('keyword', encoding='utf-8')
    que = queue.Queue()
    for keyword in keywords.readlines():
        keywordx = eval(keyword)[0]
        max_value = eval(keyword)[2]
        current_value = int(r.get(keywordx))
        print('{},{},{}'.format(keywordx, max_value, current_value))
        if max_value == current_value:
            print('"{0}"已达到上线'.format(keywordx))
        else:
            print(keyword)
            que.put(keyword)

    Threads = []

    for i in range(5):
        time.sleep(2)
        Threads.append(Main(que))

    for t in Threads:
        t.start()

    for t in Threads:
        t.join()
